package com.myself.community.service.impl;

import com.myself.community.dao.CommentMapper;
import com.myself.community.entity.Comment;
import com.myself.community.service.CommentService;
import com.myself.community.service.DiscussPostService;
import com.myself.community.utils.Code;
import com.myself.community.utils.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    SensitiveFilter sensitiveFilter;

    @Autowired
    DiscussPostService discussPostService;

    /**
     * 评论分页查询：根据评论的对象分页查询
     * @param entityType
     * @param entityId
     * @param offset
     * @param limit
     * @return
     */
    @Override
    public List<Comment> findCommentsByEntity(int entityType, int entityId, int offset, int limit) {
        return commentMapper.selectCommentsByEntity(entityType, entityId, offset, limit);
    }

    /**
     * 根据评论的对象查询评论的记录数
     * @param entityType
     * @param entityId
     * @return
     */
    @Override
    public int findCommentCount(int entityType, int entityId) {
        return commentMapper.selectCountByEntity(entityType, entityId);
    }

    /**
     * 添加评论
     * @param comment
     * @return
     */
    @Transactional
    @Override
    public int addComment(Comment comment) {
        if (comment == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        // 添加评论:需要对评论内容的标签转义、敏感词过滤
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.insertComment(comment);

        // 如果是给帖子评论：更新帖子评论数量
        if (comment.getEntityType() == Code.ENTITY_TYPE_POST) {
            //原数量
            int count = commentMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
            //更新
            discussPostService.updateCommentCount(comment.getEntityId(), count);
        }

        return rows;
    }

    @Override
    public Comment findCommentById(int id) {
        return commentMapper.selectCommentById(id);
    }
}
